<template>
  <el-card class="exam-management-card">
    <div class="card-header">
      <h2>考试管理</h2>
      <el-button 
        type="primary" 
        @click="openCreateExamDialog"
        class="create-btn"
      >
        <el-icon><Plus /></el-icon>
        新增考试
      </el-button>
    </div>

    <!-- 筛选区域 -->
    <div class="filter-container">
      <el-radio-group v-model="filterType" @change="handleFilterTypeChange">
        <el-radio label="class">按班级筛选</el-radio>
        <el-radio label="grade">按年级筛选</el-radio>
      </el-radio-group>

      <template v-if="filterType === 'class'">
        <el-select 
          v-model="selectedClassId" 
          placeholder="请选择班级"
          class="filter-select"
        >
          <el-option 
            v-for="cls in sortedTeacherClasses" 
            :key="cls.id" 
            :value="cls.id"
            :label="`${cls.grade}年级${cls.name}`"
          />
        </el-select>
      </template>

      <template v-if="filterType === 'grade'">
        <el-select 
          v-model="selectedGrade" 
          placeholder="请选择年级"
          class="filter-select"
        >
          <el-option 
            v-for="grade in uniqueGrades" 
            :key="grade" 
            :value="grade"
            :label="`${grade}年级`"
          />
        </el-select>
      </template>

      <el-date-picker
        v-model="dateRange"
        type="daterange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        format="YYYY-MM-DD HH:mm:ss"
        value-format="YYYY-MM-DD HH:mm:ss"
        class="date-picker"
      />

      <el-button type="primary" @click="fetchExams">查询</el-button>
      <el-button @click="resetFilter">重置</el-button>
    </div>

    <!-- 考试列表 -->
    <el-table 
      :data="examList" 
      border 
      stripe
      :loading="loading"
      ref="examTableRef"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="40" />
      <el-table-column prop="name" label="考试名称" width="150"/>
      <el-table-column prop="exam_grade" label="所属年级" width="90"/>
      <el-table-column 
        label="所属班级" width="100"
      >
        <template #default="scope">
        {{ scope.row.class_grade }}年级{{ scope.row.class_name }}
        </template>
      </el-table-column>
      <el-table-column prop="deadline" label="提交截止时间" />
      <el-table-column label="操作" width="300">
        <template #default="scope">
            <el-button 
              type="text" 
              size="small" 
              @click="openEditExamDialog(scope.row)"
            >
              编辑
            </el-button>
          <el-button 
            type="text" 
            size="small" 
            @click="viewStudentRanking(scope.row.exam_id)"
          >
            查看学生排名
          </el-button>
          <el-button 
            type="text" 
            size="small" 
            @click="viewGroupRanking(scope.row.exam_id)"
          >
            查看小组排名
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-card>

  <!-- 底部按钮区域 -->
  <div class="table-footer" v-if="examList.length > 0">
    <el-button
     type="primary"
     size="small"
     @click="handleViewStudentRanking"
     :disabled="selectedExamIds.length === 0"
    >
    查看学生总分排名
    </el-button>
    <el-button
     type="primary"
     size="small"
     @click="handleViewGroupRanking"
     :disabled="selectedExamIds.length === 0"
    >
    查看小组总分排名
    </el-button>
  </div>

  <!-- 学生排名对话框 -->
  <el-dialog
    v-model="studentRankingDialogVisible"
    :title="isTotalScoreRanking ? '学生总分排名' : '学生排名'"
    :width="800"
    :close-on-click-modal="false"
>
    <el-table
    :data="studentRankingList"
    border
    stripe
    :loading="studentRankingLoading"
    >
    <el-table-column 
        label="班级" 
    >
        <template #default="scope">
        {{ scope.row.class_grade }}年级{{ scope.row.class_name }}
        </template>
    </el-table-column>
    <el-table-column prop="student_number" label="学号" />
    <el-table-column prop="student_name" label="学生姓名" />
    <el-table-column prop="total_score" label="成绩" />
    <el-table-column prop="rank" label="排名" />
    <el-table-column label="操作" v-if="!isTotalScoreRanking">
        <template #default="scope">
        <el-button
            type="text"
            size="small"
            @click="handleScoreOperation(scope.row)"
            :style="{ 
            color: scope.row.total_score === 0 ? 'red' : '',
            fontWeight: scope.row.total_score === 0 ? 'bold' : ''
            }"
        >
            {{ scope.row.total_score === 0 ? '录入成绩' : '修改成绩' }}
        </el-button>
        </template>
    </el-table-column>
    </el-table>
    <template #footer>
    <el-button @click="studentRankingDialogVisible = false">关闭</el-button>
    </template>
  </el-dialog>

  <!-- 小组排名对话框 -->
  <el-dialog
    v-model="groupRankingDialogVisible"
    title="小组排名"
    :width="600"
    :close-on-click-modal="false"
  >
    <el-table
    :data="groupRankingList"
    border
    stripe
    :loading="groupRankingLoading"
    >
    <el-table-column 
        label="班级" 
    >
        <template #default="scope">
        {{ scope.row.class_grade }}年级{{ scope.row.class_name }}
        </template>
    </el-table-column>
    <el-table-column prop="group_name" label="小组名称" />
    <el-table-column prop="average_score" label="平均分" />
    <el-table-column prop="rank" label="排名" />
    </el-table>
    <template #footer>
    <el-button @click="groupRankingDialogVisible = false">关闭</el-button>
    </template>
  </el-dialog>

  <!-- 新增/编辑考试对话框 -->
  <el-dialog
    v-model="examDialogVisible"
    :title="isEditMode ? '编辑考试' : '新增考试'"
    :close-on-click-modal="false"
    @close="resetExamForm"
  >
    <el-form
      :model="examForm"
      :rules="examRules"
      ref="examFormRef"
      label-width="120px"
    >
      <!-- 考试名称 -->
      <el-form-item label="考试名称" prop="name">
        <el-input
          v-model="examForm.name"
          placeholder="请输入考试名称"
        />
      </el-form-item>

      <!-- 截止时间 -->
      <el-form-item label="截止时间" prop="deadline">
        <el-date-picker
          v-model="examForm.deadline"
          type="datetime"
          placeholder="选择截止时间"
          format="YYYY-MM-DD HH:mm:ss"
          value-format="YYYY-MM-DD HH:mm:ss"
        />
      </el-form-item>

      <!-- 范围选择：年级/班级 -->
      <el-form-item label="适用范围" prop="scopeType">
        <el-radio-group
          v-model="examForm.scopeType"
          @change="handleScopeTypeChange"
        >
          <el-radio label="grade">年级</el-radio>
          <el-radio label="class">班级</el-radio>
        </el-radio-group>
      </el-form-item>

      <!-- 年级选择器 -->
      <el-form-item
        label="选择年级"
        prop="grade"
        v-if="examForm.scopeType === 'grade'"
      >
        <el-select
          v-model="examForm.grade"
          placeholder="请选择年级"
        >
          <el-option
            v-for="grade in uniqueGrades"
            :key="grade"
            :label="`${grade}年级`"
            :value="grade"
          />
        </el-select>
      </el-form-item>

      <!-- 班级选择器 -->
      <el-form-item
        label="选择班级"
        prop="classId"
        v-if="examForm.scopeType === 'class'"
      >
        <el-select
          v-model="examForm.classId"
          placeholder="请选择班级"
        >
          <el-option
            v-for="cls in sortedTeacherClasses"
            :key="cls.id"
            :label="`${cls.grade}年级${cls.name}`"
            :value="cls.id"
          />
        </el-select>
      </el-form-item>

      <!-- 管理员口令 -->
      <el-form-item label="管理员口令" prop="adminPassword">
        <el-input
          v-model="examForm.adminPassword"
          type="password"
          placeholder="请输入管理员口令"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="examDialogVisible = false">取消</el-button>
      <el-button
        type="primary"
        @click="handleSaveExam"
        :loading="examLoading"
      >
        保存
      </el-button>
    </template>
  </el-dialog>

  <!-- 修改成绩和录入成绩共用对话框 -->
  <el-dialog
    v-model="scoreDialogVisible"
    :title="isScoreEditMode ? '修改成绩' : '录入成绩'"
    :close-on-click-modal="false"
    width="500px"
  >
    <el-form
      :model="scoreForm"
      :rules="scoreRules"
      ref="scoreFormRef"
      label-width="120px"
    >
      <!-- 学生姓名（只读） -->
      <el-form-item label="学生姓名">
        <el-input
          v-model="scoreForm.studentName"
          readonly
          placeholder="学生姓名"
        />
      </el-form-item>

      <!-- 原成绩（只读，修改模式显示） -->
      <el-form-item
        label="原成绩"
        v-if="isScoreEditMode"
      >
        <el-input
          v-model="scoreForm.oldScore"
          readonly
          placeholder="无"
        />
      </el-form-item>

      <!-- 新成绩输入框 -->
      <el-form-item label="成绩" prop="newScore">
        <el-input
          v-model.number="scoreForm.newScore"
          type="number"
          placeholder="请输入成绩"
          step="0.01"
          :precision="2"
        />
        <div class="form-hint">支持输入小数点后两位</div>
      </el-form-item>

      <!-- 管理员口令 -->
      <el-form-item
        label="管理员口令"
        prop="adminPassword"
      >
        <el-input
          v-model="scoreForm.adminPassword"
          type="password"
          placeholder="请输入管理员口令"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="scoreDialogVisible = false">取消</el-button>
      <el-button
        type="primary"
        @click="handleSaveScore"
        :loading="scoreLoading"
      >
        保存
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, reactive } from 'vue';
import { ElForm, ElMessage, ElTable, type FormRules } from 'element-plus';
import { listClasses, type ClassItem } from '../../api/classmgr';
import { 
  listExams, 
  type ListExamsParams, 
  type ExamItem, 
  type ExamStudentRankingItem,
  type ExamGroupRankingItem,
  type GetExamStudentRankingParams,
  getExamStudentRanking,
  type GetExamGroupRankingParams,
  getExamGroupRanking,
  updateExam,
  createExam,
  updateExamScore
} from '../../api/exam';

// 班级数据
const allClasses = ref<ClassItem[]>([]);
const uniqueGrades = computed(() => {
  // 提取并去重年级
  const grades = allClasses.value.map(cls => cls.grade);
  return [...new Set(grades)].sort((a, b) => a - b);
});

// 班级排序处理（新增）
const sortedTeacherClasses = computed(() => {
  // 先按年级升序，再按班级名称升序排序
  return [...allClasses.value].sort((a, b) => {
    if (a.grade !== b.grade) {
      return a.grade - b.grade;
    }
    // 假设班级名称是数字字符串，如"1班"、"2班"，提取数字进行比较
    const classA = parseInt(a.name);
    const classB = parseInt(b.name);
    return classA - classB;
  });
});

// 筛选条件
const filterType = ref<'class' | 'grade'>('class');
const selectedClassId = ref<number | undefined>(undefined);
const selectedGrade = ref<number | undefined>(undefined);
const dateRange = ref<string[]>([]);
const loading = ref(false);
const examList = ref<ExamItem[]>([]);

// 页面加载时获取数据
onMounted(async () => {
  await fetchClassList();
  await fetchExams();
});

const fetchClassList = async() => {
    try {
        const res = await listClasses();
        if (res.code === 200) {
        allClasses.value = res.content;
        } else {
        ElMessage.error(res.msg || '获取班级列表失败');
        }
    } catch (error: any) {
        ElMessage.error(error.message || '获取班级列表异常');
    }
};

// 切换筛选类型时重置对应的值
const handleFilterTypeChange = (type: 'class' | 'grade') => {
  if (type === 'class') {
    selectedGrade.value = undefined;
  } else {
    selectedClassId.value = undefined;
  }
};

// 查询考试列表
const fetchExams = async () => {
  try {
    loading.value = true;
    const params: ListExamsParams = {};
    
    // 根据筛选类型设置参数
    if (filterType.value === 'class' && selectedClassId.value) {
      params.class_id = selectedClassId.value;
    }
    if (filterType.value === 'grade' && selectedGrade.value) {
      params.grade = selectedGrade.value;
    }
    
    // 设置时间范围
    if (dateRange.value && dateRange.value.length === 2) {
      params.start_time = dateRange.value[0];
      params.end_time = dateRange.value[1];
    }
    
    const res = await listExams(params);
    if (res.code === 200) {
      examList.value = res.content;
    } else {
      ElMessage.error(res.msg || '获取考试列表失败');
    }
  } catch (error: any) {
    ElMessage.error(error.message || '获取考试列表异常');
  } finally {
    loading.value = false;
  }
};

// 重置筛选条件
const resetFilter = () => {
  filterType.value = 'class';
  selectedClassId.value = undefined;
  selectedGrade.value = undefined;
  dateRange.value = [];
  examList.value = [];
};

// 学生排名相关
const studentRankingDialogVisible = ref(false);
const studentRankingLoading = ref(false);
const studentRankingList = ref<ExamStudentRankingItem[]>([]);
const currentExamId = ref<number>(0);

// 小组排名相关
const groupRankingDialogVisible = ref(false);
const groupRankingLoading = ref(false);
const groupRankingList = ref<ExamGroupRankingItem[]>([]);

// 多个考试总分相关
const isTotalScoreRanking = ref(false);
const examTableRef = ref<InstanceType<typeof ElTable>>();
const selectedExamIds = ref<number[]>([]);

// 查看学生排名
const viewStudentRanking = async (examId: number) => {
  currentExamId.value = examId;
  studentRankingDialogVisible.value = true;
  isTotalScoreRanking.value = false;
  
  try {
    studentRankingLoading.value = true;
    const params: GetExamStudentRankingParams = {
      exam_ids: [examId],
      // 如果当前筛选条件是班级，带上班级ID
      class_id: filterType.value === 'class' ? selectedClassId.value : undefined
    };
    
    const res = await getExamStudentRanking(params);
    if (res.code === 200) {
      studentRankingList.value = res.content;
    } else {
      ElMessage.error(res.msg || '获取学生排名失败');
    }
  } catch (error: any) {
    ElMessage.error(error.message || '获取学生排名异常');
  } finally {
    studentRankingLoading.value = false;
  }
};

// 查看小组排名
const viewGroupRanking = async (examId: number) => {
  currentExamId.value = examId;
  groupRankingDialogVisible.value = true;
  
  try {
    groupRankingLoading.value = true;
    const params: GetExamGroupRankingParams = {
      exam_ids: [examId],
      class_id: undefined
    };
    
    const res = await getExamGroupRanking(params);
    if (res.code === 200) {
      groupRankingList.value = res.content;
    } else {
      ElMessage.error(res.msg || '获取小组排名失败');
    }
  } catch (error: any) {
    ElMessage.error(error.message || '获取小组排名异常');
  } finally {
    groupRankingLoading.value = false;
  }
};

// 成绩操作（录入/修改）
const handleScoreOperation = (student: ExamStudentRankingItem) => {
  // 这里可以打开成绩录入/修改对话框
  const operationType = student.total_score === 0 ? 'input' : 'edit';
  openScoreDialog({
    studentId: student.student_id,
    studentName: student.student_name,
    examId: currentExamId.value,
    currentScore: student.total_score
  }, operationType);
};

// 处理选择变化
const handleSelectionChange = (selection: ExamItem[]) => {
  selectedExamIds.value = selection.map(item => item.exam_id);
};

// 查看学生总分排名
const handleViewStudentRanking = async () => {
  studentRankingDialogVisible.value = true;
  isTotalScoreRanking.value = true;
  
  await fetchStudentRanking();
};

const fetchStudentRanking = async(examId?: number) => {
    try {
        studentRankingLoading.value = true;
        var idList: number[] = [];
        if (examId) {
            idList = [examId];
        }
        else {
            idList = selectedExamIds.value;
        }
        const params: GetExamStudentRankingParams = {
            exam_ids: idList
        };
    
        const res = await getExamStudentRanking(params);
        if (res.code === 200) {
            studentRankingList.value = res.content;
        } else {
            ElMessage.error(res.msg || '获取学生排名失败');
        }
    } catch (error: any) {
        ElMessage.error(error.message || '获取学生排名异常');
    } finally {
        studentRankingLoading.value = false;
    }
};

// 查看小组总分排名
const handleViewGroupRanking = async () => {
  groupRankingDialogVisible.value = true;
  
  try {
    groupRankingLoading.value = true;
    const params: GetExamGroupRankingParams = {
      exam_ids: selectedExamIds.value
    };
    
    const res = await getExamGroupRanking(params);
    if (res.code === 200) {
      groupRankingList.value = res.content;
    } else {
      ElMessage.error(res.msg || '获取小组排名失败');
    }
  } catch (error: any) {
    ElMessage.error(error.message || '获取小组排名异常');
  } finally {
    groupRankingLoading.value = false;
  }
};

// 新增编辑Dialog状态管理
const examDialogVisible = ref(false);
const isEditMode = ref(false);
const examLoading = ref(false);
const examFormRef = ref<InstanceType<typeof ElForm>>();

// 考试表单数据
const examForm = reactive({
  examId: 0,
  name: '',
  deadline: '',
  adminPassword: '',
  scopeType: 'grade', // 默认为年级范围
  grade: undefined,
  classId: undefined
});

// 表单验证规则
const examRules = {
  name: [{ required: true, message: '请输入考试名称', trigger: 'blur' }],
  deadline: [{ required: true, message: '请选择截止时间', trigger: 'change' }],
  scopeType: [{ required: true, message: '请选择适用范围', trigger: 'change' }],
  grade: [
    {
      required: examForm.scopeType === 'grade',
      message: '请选择年级',
      trigger: 'change'
    }
  ],
  classId: [
    {
      required: examForm.scopeType === 'class',
      message: '请选择班级',
      trigger: 'change'
    }
  ],
  adminPassword: [{ required: true, message: '请输入管理员口令', trigger: 'blur' }]
};

// 监听范围类型变化，重置对应字段
const handleScopeTypeChange = () => {
  if (examForm.scopeType === 'grade') {
    examForm.classId = undefined;
  } else {
    examForm.grade = undefined;
  }
  // 触发表单重新验证
  examFormRef.value?.clearValidate();
};

// 打开对话框（新增）
const openCreateExamDialog = () => {
  isEditMode.value = false;
  Object.assign(examForm, {
    examId: 0,
    name: '',
    deadline: '',
    adminPassword: '',
    scopeType: 'grade',
    grade: undefined,
    classId: undefined
  });
  examDialogVisible.value = true;
};

// 打开对话框（编辑）
const openEditExamDialog = (exam: any) => {
  isEditMode.value = true;
  // 判断考试原来的范围类型
  const scopeType = exam.class_id ? 'class' : 'grade';
  
  Object.assign(examForm, {
    examId: exam.exam_id,
    name: exam.name,
    deadline: exam.deadline,
    adminPassword: '', // 编辑时管理员口令需重新输入
    scopeType,
    grade: exam.grade,
    classId: exam.class_id
  });
  examDialogVisible.value = true;
};

// 保存考试信息
const handleSaveExam = async () => {
  if (!examFormRef.value) return;

  try {
    examLoading.value = true;
    await examFormRef.value.validate();

    // 构造请求参数
    const params = {
      name: examForm.name,
      deadline: examForm.deadline,
      admin_password: examForm.adminPassword,
      class_id: examForm.scopeType === 'class' ? examForm.classId : undefined,
      grade: examForm.scopeType === 'grade' ? examForm.grade : undefined
    };

    let res;
    if (isEditMode.value) {
      res = await updateExam({ ...params, exam_id: examForm.examId });
    } else {
      res = await createExam(params);
    }

    if (res.code === 200) {
      examDialogVisible.value = false;
      ElMessage.success(isEditMode.value ? '考试编辑成功' : '考试创建成功');
      // 刷新考试列表
      fetchExams();
    } else {
      ElMessage.error(res.msg || (isEditMode.value ? '编辑失败' : '创建失败'));
    }
  } catch (error: any) {
    ElMessage.error(error.message || '操作异常');
  } finally {
    examLoading.value = false;
  }
};

// 重置考试表单
const resetExamForm = () => {
  examForm.name = '';
  examForm.grade = undefined;
  examForm.classId = undefined;
  examForm.deadline = '';
  examForm.adminPassword = '';
  
  if (examFormRef.value) {
    examFormRef.value.clearValidate();
  }
};

// 成绩表单数据类型
interface ScoreForm {
  examId: number;
  studentId: number;
  studentName: string;
  oldScore?: number | null;
  newScore: number;
  adminPassword: string;
}

// 状态管理
const scoreDialogVisible = ref(false);
const isScoreEditMode = ref(false); // true:修改成绩, false:录入成绩
const scoreLoading = ref(false);
const scoreFormRef = ref<InstanceType<typeof ElForm>>();

// 表单数据
const scoreForm = reactive<ScoreForm>({
  examId: 0,
  studentId: 0,
  studentName: '',
  oldScore: null,
  newScore: 0,
  adminPassword: ''
});

// 表单验证规则
const scoreRules: FormRules<ScoreForm> = {
  newScore: [
    { required: true, message: '请输入成绩', trigger: 'blur' },
    { type: 'number', message: '请输入有效的数字', trigger: 'blur' }, // 此时 type 会被正确识别为 RuleType
    { 
      validator: (_, value: number, callback) => {
        if (value < 0) {
          callback(new Error('成绩不能为负数'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ]
};

interface OpenScoreDialogParams {
  examId: number;
  studentId: number;
  studentName: string;
  currentScore?: number | null; // 用于修改模式
}

// 打开录入成绩对话框
const openScoreDialog = (params: OpenScoreDialogParams, mode: 'edit' | 'input') => {
  isEditMode.value = mode === 'edit';
  
  // 重置表单
  Object.assign(scoreForm, {
    examId: params.examId,
    studentId: params.studentId,
    studentName: params.studentName,
    oldScore: params.currentScore ?? null,
    newScore: params.currentScore ?? 0,
    adminPassword: ''
  });
  
  scoreDialogVisible.value = true;
};

// 保存成绩
const handleSaveScore = async () => {
  if (!scoreFormRef.value) return;

  try {
    scoreLoading.value = true;
    await scoreFormRef.value.validate();

    // 构造请求参数
    const params = {
      exam_id: scoreForm.examId,
      student_id: scoreForm.studentId,
      new_score: scoreForm.newScore,
      admin_password: scoreForm.adminPassword
    };

    const res = await updateExamScore(params);
    if (res.code === 200) {
      scoreDialogVisible.value = false;
      ElMessage.success(isScoreEditMode.value ? '成绩修改成功' : '成绩录入成功');
      // 刷新排名列表
      await fetchStudentRanking(scoreForm.examId);
    } else {
      ElMessage.error(res.msg || (isScoreEditMode.value ? '修改失败' : '录入失败'));
    }
  } catch (error: any) {
    ElMessage.error(error.message || '操作异常');
  } finally {
    scoreLoading.value = false;
  }
};
</script>

<style scoped>
.exam-management-card {
  margin: 20px;
  background-color: #f0f2f5;
}

.card-header {
  margin-bottom: 15px;
  display: flex;       /* 启用Flex布局 */
  justify-content: space-between;  /* 两端对齐，标题居左，按钮居右 */
}

.card-header h2 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
}

.filter-container {
  display: flex;
  gap: 15px;
  align-items: center;
  margin-bottom: 20px;
  flex-wrap: wrap;
}

.filter-select {
  width: 200px;
}

.date-picker {
  width: 400px;
}

/* 新增底部按钮样式 */
.table-footer {
  display: flex;
  gap: 10px;
  padding: 12px 16px;
  justify-content: flex-end;
  border-top: 1px solid #eee;
  margin-top: -1px;
}

.filter-card {
  margin-bottom: 20px;
  padding: 15px;
}

.form-hint {
  color: #606266;
  font-size: 12px;
  margin-top: 5px;
}

@media (max-width: 768px) {
  .filter-container {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .filter-select, .date-picker {
    width: 100%;
  }
}
</style>